package com.heima.article.task
        ;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.service.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * @author: itheima
 * @create: 2022-01-18 11:52
 */
@Slf4j
@Service
public class ArticleTask {


    @Autowired
    private IApArticleContentService apArticleContentService;


    /**
     * freemarker.template.Configuration;
     */
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService apArticleService;


    /**
     * 创建某一篇发布文章对应HTML文件，将HTML文件上传到MinIO中得到上传后 静态HTML文件路径
     * @param articleId 文章ID
     * @throws IOException
     * @throws TemplateException
     */
    @Async
    public void createAticleHtmlAndUpload(Long articleId) {
        try {
            //1.根据文章ID 查询文章内容--模板中需要参数
            LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleContent::getArticleId, articleId);
            ApArticleContent content = apArticleContentService.getOne(queryWrapper);

            //2. 基于Freemarker技术生成静态HTML文件
            //2.1 加载模板文件 /templates/article.ftl  默认找templates文件夹下制定模板文件
            Template template = configuration.getTemplate("article.ftl");

            //2.2 定义模板所需要数据模型 [{},{},{},{}]
            HashMap<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content.getContent()));

            //2.3 调用模板引擎API将数据跟模板进行合并（将数据写入模板文件中） 得到HTML文件
            StringWriter writer = new StringWriter();
            template.process(map, writer);

            //3.将生成静态HTML文件上传到MinIO中
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload(articleId + ".html", inputStream, "text/html");

            //4.得到上传后文章静态页地址，更新文章表中：静态页字段
            LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticle::getStaticUrl, url);
            updateWrapper.eq(ApArticle::getId, articleId);
            apArticleService.update(updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成文章静态页异常:{}", e.getMessage());
        }
    }

}
